package leetcode;

import java.util.HashSet;
import java.util.Set;

/**
 * 160. 相交链表
 */
public class Solution160 {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        Set<ListNode> set = new HashSet<>();
        ListNode tempA = headA;
        ListNode tempB = headB;

        while(tempA!=null){
            set.add(tempA);
            tempA = tempA.next;
        }
        while(tempB!=null){
            if(set.contains(tempB)){
                return tempB;
            }
            tempB = tempB.next;
        }
        return null;
    }

    public ListNode getIntersectionNode2Point(ListNode headA, ListNode headB) {
        ListNode tempA = headA;
        ListNode tempB = headB;
        if(tempA==null || headB==null){
            return null;
        }
        while(tempA!=tempB){
            if(tempA==null){
                tempA = headB;
            }else{
                tempA = tempA.next;

            }
            if(tempB==null){
                tempB = headA;
            }else{
                tempB = tempB.next;
            }
        }
        return tempA;
    }
}
